import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import NotFound from '@/views/NotFound'
import Home from '@/views/Home'
import Welcome from '@/views/Welcome'
import Users from '@/views/Users'
import Rights from '@/views/Rights'
import Roles from '@/views/Roles'
import Category from '@/views/Category'
import Attribute from '@/views/Attribute'
Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/welcome',
    // 其他所有模块都要在home.vue的右边访问，所以他们对应的路由都是home的子路由
    children: [{
        path: '/welcome', // 路由地址前面加 / ,访问时就不要加/home/路由地址
        component: Welcome
      },
      {
        path: '/users',
        name: 'Users',
        component: Users
      },
      {
        path: '/rights',
        name: 'Rights',
        component: Rights
      },
      {
        path: '/roles',
        name: 'Roles',
        component: Roles
      },
      {
        path: '/categories',
        name: 'Category',
        component: Category
      },
      {
        path: '/params',
        name: 'Attribute',
        component: Attribute
      }
    ]
  },
  // 404
  {
    path: '*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
// 路由导航守卫(前置)
router.beforeEach((to, from, next) => {
  // 如果是登录或者错误的页面，直接放行
  if (to.path === '/login' || to.name === 'NotFound') {
    return next()
  }
  // 如果是其他页面，判断是否有token
  if (!window.sessionStorage.getItem('token')) {
    // 去登录页面
    Vue.prototype.$message.error('请先登录')
    return next('/login')
  }
  return next()
})

export default router
